import { AppDataSource } from "./data-source"
import { Photo } from "./entity/Photo"
import { User } from "./entity/User"

AppDataSource.initialize().then(async () => {
  // await createUser();
  // await createPhoto();

  // await queryUsers();
  // await queryPhotos();

  await queryUserByParams(1);
  await queryUserByParams({ firstName: "Timber" });
  await queryUserByParams({ age: 25 });

  await getUserByParam({ id: 2 });
  await getUserByParam({ firstName: 'Timber' });
  await getUserByParam1({ id: 4 });

  console.log("Here you can setup and run express / fastify / any other framework.")

}).catch(error => console.log(error))


async function createUser() {
  console.log("Inserting a new user into the database...")
  const user = new User()
  user.firstName = "Timber"
  user.lastName = "Saw"
  user.age = 25
  const repository = AppDataSource.manager.getRepository(User)
  await repository.save(user)
  console.log("Saved a new user with id: " + user.id)
}

async function createPhoto() {
  const photo = new Photo();
  photo.name = "Me and Bears";
  photo.description = "I am near polar bears";
  photo.filename = "photo-with-bears.jpg";
  photo.views = 1;
  photo.isPublished = true;
  const repository = AppDataSource.manager.getRepository(Photo)
  await repository.save(photo);
  console.log("Photo has been saved");
}

async function queryUsers() {
  const repository = AppDataSource.manager.getRepository(User)
  const users = await repository.find();
  console.log("Loaded users: ", users)
}

async function queryPhotos() {
  const repository = AppDataSource.manager.getRepository(Photo)
  const photos = await repository.find()
  console.log("Loaded photos: ", photos)
}

async function queryUserByParams(params: any) {
  const repository = AppDataSource.manager.getRepository(User);
  const users = await repository.find(params);
  console.log(users);
}

async function getUserByParam(params: any) {
  const repository = AppDataSource.manager.getRepository(User);
  const users = await repository.findOne({ where: params });
  console.log(users);
}

async function getUserByParam1(params: any) {
  const repository = AppDataSource.manager.getRepository(User);
  const users = await repository.findOneBy(params);
  console.log(users);
}
